package com.jiadakeji.ppm.common.utils;


import com.jiadakeji.ppm.modules.weixin.entity.WechatUnifiedorderRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author xuelongjiang
 */
public class ObjectSortAscll {


    private static Logger logger = LoggerFactory.getLogger(ObjectSortAscll.class);

    /**
     * 使用java反射机制，动态获取对象的属性和参数值，排除值为null的情况，并按字典序排序
     * @param object
     * @return
     */
    public static   String getSortMap(Object object) throws  Exception{

        Field [] fields = object.getClass().getDeclaredFields();
        Map<String,String> map = new HashMap<>();
        for(Field field : fields){
            String name = field.getName();
            String methodName = "get"+name.replaceFirst(name.substring(0, 1), name.substring(0, 1)
                    .toUpperCase());
            //通过get方法直接获取属性值
            field.setAccessible(true);
            Object value = field.get(object);
            if (value != null){
                map.put(name, value.toString());
            }


        }
        Map<String, String> sortMap = new TreeMap<String,String>(
                new Comparator<String>() {

                    @Override
                    public int compare(String arg0, String arg1) {

                        return arg0.compareTo(arg1);
                    }
                });
        sortMap.putAll(map);


        StringBuilder sortFeil = new StringBuilder();

        sortMap.forEach((k,v)-> {
            sortFeil.append(k+"="+v+"&");
        });

        sortFeil.deleteCharAt(sortFeil.length()-1);
        return sortFeil.toString();

    }

    public static   String getSortMap(Map<String,String> map) throws  Exception {

        StringBuilder sortFeil = new StringBuilder();

        map.forEach((k,v)-> {
            sortFeil.append(k+"="+v+"&");
        });

        sortFeil.deleteCharAt(sortFeil.length()-1);
        return sortFeil.toString();
    }
    /**
     * 测试 签名校验
     * @param args
     */
    public static void main(String[] args) {

        WechatUnifiedorderRequest request = new WechatUnifiedorderRequest();


        try {
            String temp = getSortMap(request);
            logger.info("没有连接key:"+getSortMap(request));
            temp = temp+"&key="+"f5e37c41c97944f1b7882a44b2c050af";
            logger.info("连接key:"+temp);
            String sign = MD5Utils.parseStrToMd5U32(temp);
            logger.info("签名sign:"+sign);
            request.setSign(sign);

            logger.info(XmlUtils.objectToXml(request));

        }catch (Exception e){

        }

    }

}
